package tw.com.diary.core;

import tw.com.diary.ae.com.DirayBussinessException;
import tw.com.diary.ae.com.Msg;
import tw.com.diary.api.com.Contract;
import tw.com.diary.api.domain.ModifyPasswordDTO;
import tw.com.diary.api.service.ModifyPasswordService;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

public class ModifyPasswordServiceImpl implements ModifyPasswordService {

	private static int MIN_PASSOWROD = 6;

	private Context context = null;

	public static ModifyPasswordService intance(Context context) {
		return new ModifyPasswordServiceImpl(context);
	}

	private ModifyPasswordServiceImpl(Context context) {
		this.context = context;
	}

	@Override
	public void modifyPassword(ModifyPasswordDTO dto) throws DirayBussinessException {

		final SharedPreferences shrare = context.getSharedPreferences(Contract.USER_SETTING, Context.BIND_AUTO_CREATE);

		final String password = shrare.getString(Contract.PASSWORD, Contract.DEF_PASSWORD);

		if (!password.equals(dto.getOldPassword())) {
			throw new DirayBussinessException(Msg.W0002);
		}

		if (!TextUtils.equals(dto.getNewPassword(), dto.getNewPassword2())) {
			throw new DirayBussinessException(Msg.W0003);
		}

		if (dto.getNewPassword().trim().length() < MIN_PASSOWROD) {

			throw new DirayBussinessException(Msg.W0004);
		}
		shrare.edit().putString(Contract.PASSWORD, dto.getNewPassword()).commit();

	}

}
